<?php
// +----------------------------------------------------------------------
// | saiadmin [ saiadmin快速开发框架 ]
// +----------------------------------------------------------------------
// | Author: your name
// +----------------------------------------------------------------------
namespace app\finance\logic;

use app\api\logic\CollectionLogic;
use plugin\saiadmin\basic\BaseLogic;
use app\finance\model\finance;
use app\cassification\model\ClassificationDictionary;
use plugin\saiadmin\service\OpenSpoutWriter;
// Import the DB facade
use think\facade\Db;

/**
 * 金融列表逻辑层
 */
class financeLogic extends BaseLogic
{
    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->model = new finance();
    }
    public function getFinance($userId,$finance_category='',$limit=10){
 
    $collectionLogic=new CollectionLogic();
        // Query financial list data
        $query = Db::table('eb_collection')
            ->leftJoin('eb_finance', 'eb_collection.collection_id = eb_finance.finance_id')
            // Bug fix: Table name mismatch, should be eb_finance instead of eb_policy
            ->leftJoin('eb_finance_institution', 'eb_finance.finance_institution = eb_finance_institution.institution_id')
            ->field('
                eb_finance.lang_code,
                eb_finance.finance_id,
                eb_finance.finance_category,
                eb_finance.start_time,
                eb_finance.end_time,
                eb_finance.finance_institution,
                eb_finance_institution.institution_name,
                eb_finance.finance_title,
                eb_finance.product_tags
            ')
            ->where('eb_finance.is_display', 1)
            ->whereNull('eb_finance.delete_time')
            ->where('eb_collection.type',5)
            ->where('eb_collection.user_id',$userId)
            ->order('eb_collection.create_time desc');

        // 当 $keyword 不为空时添加模糊查询条件
        // if (!empty($keyword)) {

        //     $query->whereLike('eb_finance.finance_title|eb_finance.institution_name','%'.$keyword.'%');
        // }
        // if (!empty($finance_institution)) {
        //     $query->where('eb_finance.finance_institution',$finance_institution);
        // }
        if(!empty($finance_category)){
            $query->where('eb_finance.finance_category',$finance_category);
        }
        $data = $query->paginate($limit);
        $lists = $data->items();

        // 遍历列表数据，补充分类名称信息
        foreach ($lists as &$item) {
            $item['is_collection']=1;
            $collectionRes=$collectionLogic->where(['type'=>1,'collection_id'=>5,'user_id'=>$userId])->findOrEmpty();
            if(!$collectionRes->isEmpty())$item['is_collection']=1;
            // 获取金融机构分类名称
            $item['finance_category_text'] = ClassificationDictionary::where('dictionary_id', $item['finance_category'])
                ->value('classification_name_' . $item['lang_code']);
            // 获取产品标签分类名称数组
            if($item['product_tags'])$item['product_tags']=json_decode($item['product_tags'], true);
            $item['product_tags_text'] = ClassificationDictionary::whereIn('dictionary_id', $item['product_tags'])
                ->column('classification_name_' . $item['lang_code']);
           
                 $now = strtotime(date('Y-m-d H:i:s'));
                  $startTime = strtotime($item['start_time']);
                  $endTime = strtotime($item['end_time']);

                  if ($now < $startTime) {
                    $item['time_text'] = '未开始';
                    $item['remaining_time_text'] = 0;
                  } elseif ($now > $endTime) {
                    $item['time_text'] = '已结束';
                    $item['remaining_time_text'] = 0;
                  } else {
                    $item['time_text'] = '进行中';
                    // 计算剩余天数，结果向上取整
                    $item['remaining_time_text'] = ceil(($endTime - $now) / (60 * 60 * 24));
                  }    
        }
        unset($item); // 解除引用

        return [
            'data' => $lists,
            'total' => $data->total()
        ];
    }

    
    /**
     * 获取金融列表
     *
     * @param string $keyword 搜索关键词
     * @param int $limit 每页数量
     * @return array 包含列表数据和总数的数组
     */
    public function getFinanceLists($lang_code='zh',$keyword = '',$finance_institution='',$finance_category='',$userId='', $limit=10)
    {
       $collectionLogic=new CollectionLogic();
        // Query financial list data
        $query = Db::table('eb_finance')
            // Bug fix: Table name mismatch, should be eb_finance instead of eb_policy
            ->rightJoin('eb_finance_institution', 'eb_finance.finance_institution = eb_finance_institution.institution_id')
            ->field('
                eb_finance.lang_code,
                eb_finance.finance_id,
                eb_finance.finance_category,
                eb_finance.start_time,
                eb_finance.end_time,
                eb_finance.finance_institution,
                eb_finance_institution.institution_name,
                eb_finance.finance_title,
                eb_finance.product_tags
            ')
            ->where('eb_finance.lang_code', $lang_code)
            ->where('eb_finance.is_display', 1)
            ->whereNull('eb_finance.delete_time')
            ->order('eb_finance.sort_order desc')
            ->order('eb_finance.create_time desc');


        // 当 $keyword 不为空时添加模糊查询条件//
        if (!empty($keyword)) {

            $query->whereLike('eb_finance.finance_title|eb_finance.product_details','%'.$keyword.'%');
        }
        if (!empty($finance_institution)) {
            $query->where('eb_finance.finance_institution',$finance_institution);
        }
        if(!empty($finance_category) && empty($keyword) ){
            $query->where('eb_finance.finance_category',$finance_category);
        }
        $data = $query->paginate($limit);
        $lists = $data->items();

        // 遍历列表数据，补充分类名称信息
        foreach ($lists as &$item) {
            $item['is_collection']=0;
            $collectionRes=$collectionLogic->where(['type'=>5,'collection_id'=>$item['finance_id'],'user_id'=>$userId])->findOrEmpty();
            if(!$collectionRes->isEmpty())$item['is_collection']=1;
            // 获取金融机构分类名称
            $item['finance_category_text'] = ClassificationDictionary::where('dictionary_id', $item['finance_category'])
                ->value('classification_name_' . $item['lang_code']);
            // 获取产品标签分类名称数组
            if($item['product_tags'])$item['product_tags']=json_decode($item['product_tags'], true);
            $item['product_tags_text'] = ClassificationDictionary::whereIn('dictionary_id', $item['product_tags'])
                ->column('classification_name_' . $item['lang_code']);
           
                 $now = strtotime(date('Y-m-d H:i:s'));
                  $startTime = strtotime($item['start_time']);
                  $endTime = strtotime($item['end_time']);

                  if ($now < $startTime) {
                    $item['time_text'] = '未开始';
                    $item['remaining_time_text'] = 0;
                  } elseif ($now > $endTime) {
                    $item['time_text'] = '已结束';
                    $item['remaining_time_text'] = 0;
                  } else {
                    $item['time_text'] = '进行中';
                    // 计算剩余天数，结果向上取整
                    $item['remaining_time_text'] = ceil(($endTime - $now) / (60 * 60 * 24));
                  }    
        }
        unset($item); // 解除引用

        return [
            'data' => $lists,
            'total' => $data->total()
        ];
    }

     public function getFinanceDetail($finance_id,$userId){
      $collectionLogic=new CollectionLogic();
       $data=Db::table('eb_finance')
          // Bug fix: Table name mismatch, should be eb_finance instead of eb_policy
          ->rightJoin('eb_finance_institution', 'eb_finance.finance_institution = eb_finance_institution.institution_id')
          ->field('
              eb_finance.finance_id,
              eb_finance.lang_code,
              eb_finance.finance_category,
              eb_finance.start_time,
              eb_finance.end_time,
              eb_finance.finance_institution,
              eb_finance_institution.institution_name,
              eb_finance.finance_title,
              eb_finance.product_tags,
              eb_finance.product_details
          ')
          ->where('finance_id', $finance_id)
          ->where('eb_finance.is_display', 1)
          ->whereNull('eb_finance.delete_time')
          ->order('eb_finance.create_time desc')
          ->find();
            if($data){
                //  $data=$data->toArray();
                 $data['finance_category_text']= ClassificationDictionary::where('dictionary_id', $data['finance_category'])->value('classification_name_'.$data['lang_code']);
                 if($data['product_tags'])$data['product_tags']=json_decode($data['product_tags'],true);
                 $data['product_tags_text']= ClassificationDictionary::whereIn('dictionary_id', $data['product_tags'])->column('classification_name_'.$data['lang_code']);
                 
                 $data['is_collection']=0;
                  $collectionRes=$collectionLogic->where(['type'=>5,'collection_id'=>$data['finance_id'],'user_id'=>$userId])->findOrEmpty();
                  if(!$collectionRes->isEmpty())$data['is_collection']=1;
                 // 获取当前时间戳
                  $now = strtotime(date('Y-m-d H:i:s'));
                  $startTime = strtotime($data['start_time']);
                  $endTime = strtotime($data['end_time']);

                  if ($now < $startTime) {
                    $data['time_text'] = '未开始';
                    $data['remaining_time_text'] = 0;
                  } elseif ($now > $endTime) {
                    $data['time_text'] = '已结束';
                    $data['remaining_time_text'] = 0;
                  } else {
                    $data['time_text'] = '进行中';
                    // 计算剩余天数，结果向上取整
                    $data['remaining_time_text'] = ceil(($endTime - $now) / (60 * 60 * 24));
                  }
                    
                }
        return $data;
    }
    public function export($where = [])
  {
      $query = $this->search($where);
      // ->field('id,name,enterprise_id,sort,status,create_time');
      $data = $this->getAll($query);
      // var_dump($data);exit();

      
      $file_name = '金融数据.xlsx';
      $header = ['金融分类', '金融机构', '开始时间', '结束时间', '展示/下架', '金融标题', '产品标签', '产品详情', '创建时间'];
      
      $filter = [
         
      ];
      $data_attr = [];
      foreach ($data as $value) {
          $data_attr[] = [
              'finance_category_text' => $value['finance_category_text'],
              'finance_institution_text' => $value['finance_institution_text'],
              'start_time' => $value['start_time'],
              'end_time' => $value['end_time'],
              'is_display_text' => $value['is_display']?'展示':'下架',
              'finance_title' => $value['finance_title'],
              'product_tags_text' => $value['product_tags_text'],

              'product_details' => $value['product_details'],
              'create_time' => $value['create_time']
          ];
      }

      $writer = new OpenSpoutWriter($file_name);
      $writer->setWidth([20, 20, 20, 20, 20, 20, 20, 50, 20]);
      $writer->setHeader($header);
      $writer->setData($data_attr, null, $filter);
      $file_path = $writer->returnFile();
      return response()->download($file_path, urlencode($file_name));
  }

}
